class CourseStagePanel {
    constructor(app) {
        this.app = app;
        this.modal = null;
        this.currentMode = null;
    }

    initCourseStageManagement() {
        const stagePanel = document.getElementById('course-stage-panel');

        // 添加阶段按钮功能
        const addStageBtn = stagePanel.querySelector('#add-stage-btn');
        if (addStageBtn) {
            addStageBtn.addEventListener('click', () => this.showStageModal('add'));
        }

        // 搜索功能
        const searchInput = stagePanel.querySelector('.search-input');
        if (searchInput) {
            searchInput.addEventListener('input', (e) => this.handleStageSearch(e));
        }
    }

    // ==================== 课程阶段管理 ====================
    async loadCourseStages() {
        try {
            const response = await this.app.authenticatedFetch('/api/web/course/getAllStage');
            const result = await response.json();

            if (result.code === 200) {
                const stages = result.data || [];
                const tbody = document.querySelector('#stages-table-body');
                tbody.innerHTML = "";

                // 加载行模板
                const rowTemplateResponse = await fetch('/templates/stage-row.html');
                const rowTemplateText = await rowTemplateResponse.text();

                // 使用DOMParser解析模板
                const parser = new DOMParser();
                const doc = parser.parseFromString(rowTemplateText, 'text/html');
                const rowElement = doc.querySelector('tbody tr');

                // 检查模板是否正确加载
                if (!rowElement) {
                    throw new Error('阶段行模板加载失败，找不到<tr>元素');
                }

                stages.forEach(stage => {
                    const row = rowElement.cloneNode(true);
                    const defaultAvatarUrl = Utils.buildFullUrl('/images/default-avatar.png');

                    // 使用ID直接获取并填充数据，添加检查确保元素存在
                    const stageIdElement = row.querySelector('#stage-id');
                    if (stageIdElement) {
                        stageIdElement.textContent = stage.id;
                    }

                    const stageTitleElement = row.querySelector('#stage-title');
                    if (stageTitleElement) {
                        stageTitleElement.textContent = stage.title;
                    }

                    // 处理封面图片
                    const stageCoverElement = row.querySelector('#stage-cover');
                    if (stageCoverElement && stage.cover) {
                        const img = document.createElement('img');
                        img.src = stage.cover;
                        img.alt = '封面';
                        img.style.cssText = 'max-width: 100px; max-height: 60px;';
                        img.setAttribute('data-default', defaultAvatarUrl);
                        img.addEventListener('error', function() {
                            this.src = this.getAttribute('data-default');
                        });
                        stageCoverElement.appendChild(img);
                    }

                    const stageSynopsisElement = row.querySelector('#stage-synopsis');
                    if (stageSynopsisElement) {
                        stageSynopsisElement.textContent = stage.synopsis || '';
                    }

                    const stageCreateDateElement = row.querySelector('#stage-create-date');
                    if (stageCreateDateElement) {
                        stageCreateDateElement.textContent = Utils.formatDate(stage.create_date) || '';
                    }

                    const stageUpdateDateElement = row.querySelector('#stage-update-date');
                    if (stageUpdateDateElement) {
                        stageUpdateDateElement.textContent = Utils.formatDate(stage.updata_date) || '';
                    }

                    // 设置按钮属性
                    const viewBtn = row.querySelector('#stage-view-btn');
                    if (viewBtn) {
                        viewBtn.setAttribute('data-id', stage.id);
                        viewBtn.setAttribute('data-title', stage.title);
                    }

                    const editBtn = row.querySelector('#stage-edit-btn');
                    if (editBtn) {
                        editBtn.setAttribute('data-id', stage.id);
                        editBtn.setAttribute('data-title', stage.title);
                        editBtn.setAttribute('data-synopsis', stage.synopsis || '');
                        editBtn.setAttribute('data-cover', stage.cover || '');
                    }

                    const deleteBtn = row.querySelector('#stage-delete-btn');
                    if (deleteBtn) {
                        deleteBtn.setAttribute('data-id', stage.id);
                    }

                    tbody.appendChild(row);
                });

                // 在所有行添加到DOM后再绑定事件监听器
                tbody.querySelectorAll('#stage-view-btn').forEach(button => {
                    button.addEventListener('click', (e) => {
                        const stageId = e.target.getAttribute('data-id');
                        const stageTitle = e.target.getAttribute('data-title');
                        this.selectCourseSubPanel(stageId, stageTitle);
                    });
                });

                // 绑定所有编辑按钮事件
                tbody.querySelectorAll('#stage-edit-btn').forEach(button => {
                    button.addEventListener('click', (e) => {
                        const stageData = {
                            id: parseInt(e.target.getAttribute('data-id')),
                            title: e.target.getAttribute('data-title'),
                            synopsis: e.target.getAttribute('data-synopsis'),
                            cover: e.target.getAttribute('data-cover')
                        };
                        this.showStageModal('edit', stageData);
                    });
                });

                // 绑定所有删除按钮事件
                tbody.querySelectorAll('#stage-delete-btn').forEach(button => {
                    button.addEventListener('click', (e) => {
                        const stageId = parseInt(e.target.getAttribute('data-id'));
                        const stageTitle = e.target.closest('tr').querySelector('#stage-title').textContent;
                        Utils.confirmAndDelete(stageTitle, () => this.deleteStage(stageId, stageTitle));
                    });
                });

                // 重新绑定搜索功能
                const searchInput = document.querySelector('#course-stage-panel .search-input');
                if (searchInput) {
                    searchInput.addEventListener('input', (e) => this.handleStageSearch(e));
                }

                // 如果没有阶段，显示提示信息
                if (stages.length === 0) {
                    const row = document.createElement('tr');
                    row.innerHTML = `<td colspan="7" style="text-align: center;">暂无课程阶段</td>`;
                    tbody.appendChild(row);
                }
            } else {
                console.error('获取课程阶段失败:', result.msg);
                Utils.showError(document.querySelector('#stages-table-body'), '获取课程阶段失败');
            }
        } catch (error) {
            console.error('加载课程阶段数据失败:', error);
            Utils.showError(document.querySelector('#stages-table-body'), '加载课程阶段数据失败: ' + error.message);
        }
    }

    selectCourseSubPanel(stageId, stageTitle) {
        // 设置当前选中的阶段
        this.app.currentStage = { id: stageId, title: stageTitle };

        // 切换到课程面板
        this.app.switchSubPanel('course');

        // 加载该阶段下的课程
        this.app.courseSectionPanel.loadCoursesForStage(stageId);
    }

    async initStageModal(mode) {
        try {
            // 加载外部模态框模板
            const response = await fetch('/templates/stage-modal.html');
            const template = await response.text();
            
            // 创建模态框
            if (!this.modal) {
                this.modal = document.createElement('div');
                this.modal.className = 'modal';
                this.modal.id = 'stage-modal';
                document.body.appendChild(this.modal);
            }
            
            this.modal.innerHTML = template;
            
            // 设置标题和按钮文本
            const titleElement = this.modal.querySelector('h3');
            const submitButton = this.modal.querySelector('.btn.primary');
            
            if (mode === 'add') {
                if (titleElement) {
                    titleElement.textContent = '添加课程阶段';
                }
                if (submitButton) {
                    submitButton.textContent = '添加';
                }
            } else if (mode === 'edit') {
                if (titleElement) {
                    titleElement.textContent = '编辑课程阶段';
                }
                if (submitButton) {
                    submitButton.textContent = '更新';
                }
            }
            
            this.currentMode = mode;
            return this.modal;
        } catch (error) {
            console.error('加载阶段模态框模板失败:', error);
            return null;
        }
    }

    showStageModal(mode, stageData = null) {
        // 检查模式是否有效
        if (mode !== 'add' && mode !== 'edit') {
            console.error('无效的模式:', mode);
            return;
        }
        
        // 初始化模态框
        this.initStageModal(mode).then(modal => {
            if (!modal) {
                console.error('无法加载阶段模态框模板');
                alert('无法打开阶段模态框，请稍后重试');
                return;
            }

            // 获取表单元素
            const form = modal.querySelector('#stage-form');
            const idInput = modal.querySelector('#stage-id');
            const titleInput = modal.querySelector('#stage-title');
            const synopsisInput = modal.querySelector('#stage-synopsis');
            const coverInput = modal.querySelector('#stage-cover');
            const previewContainer = modal.querySelector('#stage-cover-preview');
            const closeBtn = modal.querySelector('.close');
            const cancelBtn = modal.querySelector('#cancel-stage');

            // 移除之前可能存在的事件监听器
            if (this.currentCloseHandler) {
                closeBtn.removeEventListener('click', this.currentCloseHandler);
            }
            if (this.currentCancelHandler) {
                cancelBtn.removeEventListener('click', this.currentCancelHandler);
            }
            if (this.currentFormSubmitHandler) {
                form.removeEventListener('submit', this.currentFormSubmitHandler);
            }
            if (this.currentCoverChangeHandler) {
                coverInput.removeEventListener('change', this.currentCoverChangeHandler);
            }

            // 根据模式填充表单数据
            if (mode === 'edit' && stageData) {
                // 编辑模式
                if (idInput) {
                    idInput.value = stageData.id;
                }
                
                if (titleInput) {
                    titleInput.value = stageData.title;
                }
                
                if (synopsisInput) {
                    synopsisInput.value = stageData.synopsis || '';
                }
                
                // 添加封面预览（如果有）
                if (previewContainer) {
                    if (stageData.cover) {
                        const defaultAvatarUrl = Utils.buildFullUrl('/images/default-avatar.png');
                        previewContainer.innerHTML = `<img src="${stageData.cover}" style="max-width: 200px; max-height: 200px; margin-top: 10px;" alt="当前封面" data-default="${defaultAvatarUrl}">`;
                        
                        // 为图片绑定错误处理事件
                        const previewImg = previewContainer.querySelector('img');
                        if (previewImg) {
                            previewImg.addEventListener('error', function() {
                                this.src = this.getAttribute('data-default');
                            });
                        }
                    } else {
                        previewContainer.innerHTML = '';
                    }
                }
            } else {
                // 添加模式
                // 清空字段
                if (idInput) {
                    idInput.value = '';
                }
                
                if (titleInput) {
                    titleInput.value = '';
                }
                
                if (synopsisInput) {
                    synopsisInput.value = '';
                }
                
                if (previewContainer) {
                    previewContainer.innerHTML = '';
                }
            }

            const closeModal = () => {
                modal.style.display = 'none';
            };

            // 绑定关闭事件
            if (closeBtn) {
                this.currentCloseHandler = closeModal;
                closeBtn.addEventListener('click', closeModal);
            }

            if (cancelBtn) {
                this.currentCancelHandler = closeModal;
                cancelBtn.addEventListener('click', closeModal);
            }

            // 图片预览功能
            if (coverInput) {
                this.currentCoverChangeHandler = (e) => Utils.handleImagePreview(e, 'stage-cover-preview');
                coverInput.addEventListener('change', this.currentCoverChangeHandler);
            }

            // 表单提交事件
            if (form) {
                this.currentFormSubmitHandler = (e) => this.handleStageSubmit(e, mode);
                form.addEventListener('submit', this.currentFormSubmitHandler);
            }

            // 显示模态框
            modal.style.display = 'block';
        });
    }

    async handleStageSubmit(e, mode) {
        e.preventDefault();
        
        const id = this.modal.querySelector('#stage-id').value;
        const title = this.modal.querySelector('#stage-title').value;
        const synopsis = this.modal.querySelector('#stage-synopsis').value;
        const stageCoverElement = this.modal.querySelector('#stage-cover');
        const coverFile = stageCoverElement && stageCoverElement.files ? stageCoverElement.files[0] : null;

        // 验证必填字段
        if (!title.trim()) {
            alert('请输入阶段标题');
            return;
        }

        // 创建FormData对象
        const formData = new FormData();
        formData.append('title', title.trim());
        formData.append('synopsis', synopsis.trim());
        
        if (coverFile) {
            formData.append('cover', coverFile);
            // 设置封面裁剪尺寸
            formData.append('coverWidth', 288);
            formData.append('coverHeight', 378);
        }

        if (mode === 'edit') {
            formData.append('id', id);
        }

        try {
            const url = mode === 'add' ? '/api/web/course/addStage' : '/api/web/course/updateStage';
            const response = await this.app.authenticatedFetch(url, {
                method: 'POST',
                body: formData
            });

            const resultText = await response.text();
            
            let result;
            try {
                result = JSON.parse(resultText);
            } catch (parseError) {
                console.error('解析响应失败:', resultText);
                throw new Error('服务器响应格式错误');
            }
            
            if (result.code === 200) {
                alert('课程阶段' + (mode === 'add' ? '添加' : '更新') + '成功');
                // 关闭模态框
                if (this.modal) {
                    this.modal.style.display = 'none';
                }
                // 重新加载课程阶段列表
                this.loadCourseStages();
            } else {
                alert('操作失败: ' + (result.msg || '未知错误'));
            }
        } catch (error) {
            console.error('操作课程阶段失败:', error);
            alert('操作课程阶段失败: ' + error.message);
        }
    }

    async deleteStage(stageId, stageTitle) {
        try {
            const response = await this.app.authenticatedFetch(`/api/web/course/deleteStage/${stageId}`, {
                method: 'DELETE'
            });

            const resultText = await response.text();

            let result;
            try {
                result = JSON.parse(resultText);
            } catch (parseError) {
                console.error('解析响应失败:', resultText);
                throw new Error('服务器响应格式错误');
            }

            if (result.code === 200) {
                alert(`课程阶段"${stageTitle}"删除成功`);
                // 重新加载课程阶段列表
                this.loadCourseStages();
            } else {
                alert('删除失败: ' + (result.msg || '未知错误'));
            }
        } catch (error) {
            console.error('删除课程阶段失败:', error);
            alert('删除课程阶段失败: ' + error.message);
        }
    }

    handleStageSearch(e) {
        const searchTerm = e.target.value.toLowerCase();
        const stageRows = document.querySelectorAll('#stages-table-body tr');

        stageRows.forEach(row => {
            const title = row.querySelector('#stage-title').textContent.toLowerCase();
            const synopsis = row.querySelector('#stage-synopsis').textContent.toLowerCase();

            if (title.includes(searchTerm) || synopsis.includes(searchTerm)) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });
    }
}